<template>
  <div class="login-container">
    <el-form :model="loginForm" @submit.native.prevent="onLogin" class="login-form">
      <h2>用户登录</h2>
      <el-form-item>
        <el-input v-model="loginForm.username" placeholder="用户名" />
      </el-form-item>
      <el-form-item>
        <el-input v-model="loginForm.password" type="password" placeholder="密码" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onLogin" :loading="loading">登录</el-button>
        <el-button type="text" @click="$router.push('/register')">注册</el-button>
      </el-form-item>
      <el-alert v-if="error" :title="error" type="error" show-icon></el-alert>
    </el-form>
  </div>
</template>

<script>
import api from '@/api';
import { mapMutations } from 'vuex';
export default {
  data() {
    return {
      loginForm: { username: '', password: '' },
      loading: false,
      error: ''
    };
  },
  methods: {
    ...mapMutations(['setToken', 'setRole']),
    async onLogin() {
      this.loading = true;
      this.error = '';
      try {
        const res = await api.post('/auth/login', this.loginForm);
        this.setToken(res.token);
        this.setRole(res.role);
        this.$router.push('/home');
      } catch (e) {
        this.error = '用户名或密码错误';
      }
      this.loading = false;
    }
  }
};
</script>

<style scoped>
.login-container { max-width: 400px; margin: 100px auto; }
.login-form { background: #fff; padding: 30px; border-radius: 8px; box-shadow: 0 2px 8px #eee; }
</style>
